﻿using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
using Foundation.ExtensionMethods;

namespace Foundation.MarkupExtensions
{
    public class LocalizedBinding : Localizing
    {
        public Binding Binding { get; set; }

        public LocalizedBinding(string key) : base(key) { }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var service = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
            var targetObject = service.TargetObject;
            var targetProperty = service.TargetProperty;
            var frameworkElement = targetObject as FrameworkElement;
            var dependancyProperty = targetProperty as DependencyProperty;
            var binding1 = ProvideBinding(serviceProvider);
            if (dependancyProperty != null)
            {
                if (frameworkElement == null)
                    return this;

                TargetObject = new WeakReference(frameworkElement);
                TargetUpdated += () =>
                {
                    if (Key == null) return;
                    var target = TargetObject.Target as FrameworkElement;
                    if (target == null) return;
                    var binding = ProvideBinding(serviceProvider);
                    target.SetBinding(dependancyProperty, binding);
                };
            }

            return binding1 == null ? base.ProvideValue(serviceProvider) : binding1.ProvideValue(serviceProvider);
        }

        private Binding ProvideBinding(IServiceProvider serviceProvider)
        {
            if (Binding == null) return null;
            var binding = Binding.Clone();
            var localizedValue =
                base.ProvideValue(serviceProvider) as string ?? string.Empty;
            if (binding.StringFormat != null)
                binding.StringFormat = binding.StringFormat.Replace("{L}", localizedValue);
            return binding;
        }
    }
}
